var center = new GLatLng(0,15);
var zoom = 3;
var map;
var markersArray = [];
var popsArray = [];
var pops2Array = [];
var currentOption = [];
var baseIcon = new GIcon();
baseIcon.iconSize=new GSize(32,32);
baseIcon.shadowSize=new GSize(56,32);
baseIcon.iconAnchor=new GPoint(16,32);
baseIcon.infoWindowAnchor=new GPoint(16,0);

function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.setCenter(center, zoom);
		map.addControl(new GLargeMapControl());
		call("./functors/displayRegionsFunctor.php", new Array());
		var crossLayer = new GTileLayer(new GCopyrightCollection(""), 0, 15);
		var layerTerCross = [ G_PHYSICAL_MAP.getTileLayers()[0],
                              crossLayer ];
        var mtTerCross = new GMapType(layerTerCross,
                                      G_PHYSICAL_MAP.getProjection(), "Ter+");
		map.setMapType(mtTerCross);
	}
}

function displayReport(text) {
	$('report_text').innerHTML=text;
}

function setTitle(title) {
	$('report_title').innerHTML=title;
}

function displayRegions(XML) {
	createMarkers((GXml.parse(XML)));
}

function displayPopulations(XML,sid) {
	var xml = GXml.parse(XML);
	var markers = xml.documentElement.getElementsByTagName("marker");
	for (var j = 0; j < popsArray.length; j++) {
		map.removeTLabel(popsArray[j]);
	}
	popsArray = [];
	for (var j = 0; j < pops2Array.length; j++) {
		map.removeTLabel(pops2Array[j]);
	}
	pops2Array = [];
	for (var i = 0; i < markers.length; i++) {
		var info = markers[i].getElementsByTagName("info")[0];
		var id = info.getAttribute("region");
		var label = new TLabel();
		label.id = id;
		label.anchorLatLng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
		label.anchorPoint = 'center';
		label.content = (new XMLSerializer()).serializeToString(info);
		label.addclass = "labels";
		map.addTLabel(label);
		popsArray.push(id);
	}
	if (sid) {
		$('currentlyViewing').innerHTML = sid;
	}
}

function comparePopulations(XML,sid) {
	var xml = GXml.parse(XML);
	var markers = xml.documentElement.getElementsByTagName("marker");
	for (var j = 0; j < pops2Array.length; j++) {
		map.removeTLabel(pops2Array[j]);
	}
	pops2Array = [];
	for (var i = 0; i < markers.length; i++) {
		var info = markers[i].getElementsByTagName("info")[0];
		var id = info.getAttribute("region")+"2";
		var label = new TLabel();
		label.id = id;
		label.anchorLatLng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
		label.anchorPoint = 'center';
		label.content = (new XMLSerializer()).serializeToString(info);
		label.addclass = "labels blue";
		map.addTLabel(label);
		pops2Array.push(id);
	}
	if (sid) {
		var now = $('currentlyViewing').innerHTML;
		$('currentlyViewing').innerHTML = now+","+sid;
	}
}

function getCurrentSpecies(first) {
	var current = $('currentlyViewing').innerHTML;
	var species = current.split(",");
	if (species[0]) {
		var r = "selectSpecies="+species[0];
		if (first == 1) {
			var r = "sid="+species[0];
		}
	}
	if (species[1]) {
		var r = "firstSpecies="+species[0]+"&secondSpecies="+species[1];
		if (first == 1) {
			var r = "sid="+species[0];
		}
	}
	return r;
}

function setCurrentSpecies(one,two) {
	var current = $('currentlyViewing');
	var HTML = one;
	if (two) {
		HTML += ","+two;
	}
	current.innerHTML = HTML;
}

function call(file, args, loading, updatePopulation) {
	var xmlHttp = GXmlHttp.create();
	var params = "";
	for (var i = 0; i < args.length; i++) {
		params += args[i]+"&";
	}
	xmlHttp.onreadystatechange=function() {
		if (loading == 1) {
			if (xmlHttp.readyState==1) {
			show('loading');
			}
			if (xmlHttp.readyState==4) {
				hide('loading');
				eval(xmlHttp.responseText);
				if (updatePopulation == 1) {
					if (params.indexOf('secondSpecies') != -1) {
						call("./functors/compareSpeciesFunctor.php",args,0,0);
					} else {
						call("./functors/displayPopulationFunctor.php",args,0,0);
					}
				}
				
			}
		} else {
			if (xmlHttp.readyState==4) {
				eval(xmlHttp.responseText);
			}
			if (updatePopulation == 1) {
				if (params.indexOf('secondSpecies') != -1) {
					call("./functors/compareSpeciesFunctor.php",args,0,0);
				} else {
					call("./functors/displayPopulationFunctor.php",args,0,0);
				}
			}
		}
	}
	xmlHttp.open("POST",file,true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", args.length);
    xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params);
}

function createMarkers(xml) {
	var markers = xml.documentElement.getElementsByTagName("marker");
	for (var i = 0; i < markers.length; i++) {
		var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
		var info = markers[i].getElementsByTagName("info")[0];
		map.addOverlay(createMarker(latlng,info));
	}
}

function createMarker(point,info) {
	var icon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal4/icon49.png", null, "http://maps.google.com/mapfiles/kml/pal4/icon49s.png");
	var marker = new GMarker(point,icon);
	if (marker) {
		if (info != '' && info != null) {
			GEvent.addListener(marker, "click", function() {
				var s = new Array("rid="+info.getAttribute('name'));
				setTitle("<h2>Region: "+(new XMLSerializer()).serializeToString(info)+"</h2>");
				call('./functors/regionReportFunctor.php',s,1,0);
			});
		}
		markersArray.push(marker);
	}
	return marker;
}

function showOption(name) {
	for (var i = 0; i < currentOption.length; i++) {
		hide(currentOption[i]);
	}
	currentOption = [];
	var selected = name.split("-");
	for (var j = 0; j < selected.length; j++) {
		show(selected[j]);
		currentOption.push(selected[j]);
	}
	show('popupBG');
}

function hideOptions() {
	for (var i = 0; i < currentOption.length; i++) {
		hide(currentOption[i]);
	}
	currentOption = [];
	hide('popupBG');
}

function $(id) {return document.getElementById(id);}

function show(id) {
	$(id).style.display='block';
}

function hide(id) {
	$(id).style.display='none';
}

function refreshEvents() {
	var xmlHttp = GXmlHttp.create();
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4) {
			$('options_envevent').innerHTML = xmlHttp.responseText;
			$('options_envevent2').innerHTML = xmlHttp.responseText;
		}
	}
	xmlHttp.open("POST","functors/populateEnvironmentEventFunctor.php",true);
	xmlHttp.send(null);
}